#include <iostream>
#include <memory>
#include <sys/poll.h>
#include "Log.hpp"
#include "Socket.hpp"

using namespace SocketModule;
using namespace LogModule;

class PollServe
{
    const static int size = 4096;
    const static int defaultfd = -1;

public:
    PollServe(int port)
        : _listen_sock(std::make_unique<TcpSocket>()), _isrunning(false)
    {
        _listen_sock->BulidListenSocketMethod(port);
        for (int i = 0; i < size; i++)
        {
            _fds[i].fd = defaultfd;
            _fds[i].events = 0;
            _fds[i].revents = 0;
        }
        _fds[0].fd = _listen_sock->Fd();
        _fds[0].events = POLLIN;
    };
    ~PollServe() {};

    void Start()
    {
        int timeout = 1000;
        _isrunning = true;
        while (_isrunning)
        {
            // fd_set rfds;
            // FD_ZERO(&rfds);
            // int maxfd=defaultfd;
            // for(int i=0;i<size;i++)
            // {
            //     if(_fd_arry[i]==defaultfd) continue;
            //     FD_SET(_fd_arry[i],&rfds);
            //     if(maxfd<_fd_arry[i]) maxfd=_fd_arry[i];
            // }

            // struct timeval timeout{2,0};
            int n = poll(_fds, size, timeout);
            switch (n)
            {
            case -1:
                LOG(LogLevel::ERROR) << "select error";
                break;
            case 0:
                LOG(LogLevel::ERROR) << "time out.....";
                break;
            default:
                LOG(LogLevel::INFO) << "事件就绪，就绪个数n: " << n;
                Dispatcher();
                break;
            }
        }
        _isrunning = false;
    }

    void Dispatcher()
    {
        for (int i = 0; i < size; i++)
        {
            if (_fds[i].fd == defaultfd)
                continue;
            if (_fds[i].revents & POLLIN)
            {
                if (_fds[i].fd == _listen_sock->Fd())
                {
                    Accepter();
                }
                else
                {
                    Recver(i);
                }
            }
        }
    }

private:
    std::unique_ptr<Socket> _listen_sock;
    bool _isrunning;
    struct pollfd _fds[size];

public:
    void IsStop() { _isrunning = false; }
    void Accepter()
    {
        InetAddr client;
        int fd = _listen_sock->Accept(&client);
        if (fd >= 0)
        {
            LOG(LogLevel::INFO) << "get  new link,sockfd: " << fd << "  client is" << client.StringAddr();
        }
        int pos = 0;
        for (; pos < size; pos++)
        {
            if (_fds[pos].fd == defaultfd)
                break;
        }
        if (pos == size)
        {
            LOG(LogLevel::WARNING) << "poll serve full";
            close(fd);
        }
        else
        {
            _fds[pos].fd = fd;
            _fds[pos].events = POLLIN;
        }
    }

    void Recver(int pos)
    {
        char buffer[1024];
        ssize_t n = recv(_fds[pos].fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
        else if (n == 0)
        {
            LOG(LogLevel::INFO) << "client quit....";
             close(_fds[pos].fd);
            _fds[pos].fd = defaultfd;
            _fds[pos].events = 0;
           
        }
        else
        {
            LOG(LogLevel::ERROR) << "recv error....";
        } 
    }
};